#!/bin/bash

# 设置环境变量
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

# 目录路径
REMOTE_DEPLOY_DIR="/opt/apps/bones-app"
LOG_DIR="${REMOTE_DEPLOY_DIR}/logs"
PID_DIR="${REMOTE_DEPLOY_DIR}/pids"
REMOTE_JDK_PATH="/opt/java/jdk-21.0.5"
JAR_NAME="bones-app.jar"

# 设置远程 JDK 路径
export JAVA_HOME=${REMOTE_JDK_PATH}
export PATH=$JAVA_HOME/bin:$PATH

# 创建部署和日志目录
mkdir -p ${REMOTE_DEPLOY_DIR}
mkdir -p ${LOG_DIR}
mkdir -p ${PID_DIR}
mkdir -p ${REMOTE_DEPLOY_DIR}/heapdumps

# 启动/停止/重启操作
case $1 in
  start)
    echo "Starting application..."

    # 删除旧的 JAR 文件（仅在 start 或 restart 时）
    if [ -f ${REMOTE_DEPLOY_DIR}/${JAR_NAME} ]; then
        echo "Removing old JAR file..."
        rm -f ${REMOTE_DEPLOY_DIR}/${JAR_NAME}
    fi

    # 启动新进程
    cd ${REMOTE_DEPLOY_DIR}
    nohup java -Xms256m -Xmx512m -XX:+UseZGC -XX:MaxRAMPercentage=75.0 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${REMOTE_DEPLOY_DIR}/heapdumps -Djava.security.egd=file:/dev/./urandom -Dfile.encoding=UTF-8 -jar ./${JAR_NAME} > /dev/null 2>&1 &

    # 保存PID
    echo $! > ${PID_DIR}/app.pid
    ;;

  stop)
    echo "Stopping application..."

    # 检查并杀掉旧进程
    if [ -f ${PID_DIR}/app.pid ]; then
        PID=$(cat ${PID_DIR}/app.pid)
        if ps -p $PID > /dev/null 2>&1; then
            echo "Killing process with PID $PID"
            kill -9 $PID || true
        else
            echo "Process with PID $PID does not exist"
        fi
        rm -f ${PID_DIR}/app.pid
    else
        echo "No running application found"
    fi
    ;;

  restart)
    echo "Restarting application..."

    # 先停止
    $0 stop

    # 删除旧的 JAR 文件
    if [ -f ${REMOTE_DEPLOY_DIR}/${JAR_NAME} ]; then
        echo "Removing old JAR file..."
        rm -f ${REMOTE_DEPLOY_DIR}/${JAR_NAME}
    fi

    # 启动新进程
    $0 start
    ;;

  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
    ;;
esac
